package bitcarve.hydra.ui.timeline.viewer
{
	import bitcarve.hydra.core.track.core.SampleTrack;
	import bitcarve.hydra.ui.timeline.layout.ITrackLayout;
	import bitcarve.hydra.ui.timeline.layout.LayoutUpdateEvent;
	import bitcarve.hydra.ui.timeline.layout.TrackLayoutItem;
	import bitcarve.hydra.ui.timeline.render.SimpleColorTrackRender;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.utils.Dictionary;
	
	public class TrackViewer extends Sprite implements IViewer
	{
		public 	var trackRender:SimpleColorTrackRender;
		private var freeRenders:Array;
		private var visibleRenderers:Dictionary;
		private var layout:ITrackLayout;
		
		
		public function TrackViewer()
		{
			trackRender = new SimpleColorTrackRender();
			freeRenders = new Array();
			visibleRenderers = new Dictionary();
		}
		
		public function update( event : LayoutUpdateEvent ):void
		{
			layout = event.layout as ITrackLayout;
			render(layout);
			trace("track viewer update");
		}
		
		
		private function render( layout : ITrackLayout ) : void 
		{
			if( layout == null ) return;
			
			var oldRenderers : Dictionary = visibleRenderers;
			visibleRenderers = new Dictionary();
			
			for each( var item : TrackLayoutItem in layout.items )
			{
				var renderer : SimpleColorTrackRender = oldRenderers[ item ];
				if( renderer != null )
				{
					renderer.x = item.x / item.zoom;
					renderer.y = item.y - layout.yPosition + 2;
					renderer.width = item.width / item.zoom;
					renderer.height = item.height - 4;
					renderer.color = (item.data as SampleTrack).color;
					delete oldRenderers[ item ];
				}
				else 
				{
					renderer = new SimpleColorTrackRender();
					renderer.x = item.x / item.zoom;
					renderer.y = item.y + 2;
					renderer.width = item.width / item.zoom;
					renderer.height = item.height - 4;
					renderer.color = (item.data as SampleTrack).color;
					
					addChild( DisplayObject( renderer ) );
					renderer.data = item.data;
				}
				renderer.render();
				visibleRenderers[ item ] = renderer;
			}
			
			removeUnusedRenderers( oldRenderers );			
			updateSelection();
		}
		
		private function removeUnusedRenderers( oldRenderers : Dictionary ) : void
		{
			for each( var freeRender : DisplayObject in oldRenderers )
			{
				freeRenders.push( removeChild( freeRender ));
			}
		}
		
		private function updateSelection() : void
		{
//			for each( var renderer : IScheduleEntryRenderer in visibleRenderers )
//			{
//				renderer.selected = selection.hasItem( renderer.data );
//			}
		}
	}
}